package com.ving.test.nativemybatis.plugin;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;


/**
 * Created by liuweijie on 2019-11-12.
 */
@Intercepts({
        @Signature(type = Executor.class,method = "query",args={MappedStatement.class,Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class,method = "update",args={MappedStatement.class,Object.class})
})
@Slf4j
public class MyPlugin  implements Interceptor {


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
        Object parameterObject = null;
        if(invocation.getArgs().length>1){
            parameterObject=invocation.getArgs()[1];
        }
        long start = System.currentTimeMillis();
        Object result = invocation.proceed();
        String statementId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
        Configuration configuration = mappedStatement.getConfiguration();
        String sql = getsql(boundSql,parameterObject,configuration);

        long end = System.currentTimeMillis();
        long timing = end -start;
        if(log.isInfoEnabled()){
            log.info("执行sql耗时："+timing+"ms"+" - id:"+statementId+"- sql:");
            log.info("   "+sql);
        }

        return result;
    }

    private String getsql(BoundSql boundSql, Object parameterObject, Configuration configuration) {
        return boundSql.getSql()+"  "+parameterObject.toString();
    }
}
